<template>
  <div class="wrapper">
    <el-form ref="editRole" :model="editData" :rules="rules" label-width="80px">
      <el-form-item label="英文名称" prop="name">
        <el-input class="w500" v-model="editData.name" placeholder="例如：editor"></el-input>
      </el-form-item>
      <el-form-item label="中文名称" prop="name_cn">
        <el-input class="w500" v-model="editData.name_cn" placeholder="例如：编辑者"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="editRole('editRole')">提交</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import notify from '@/tools/notify'

export default {
  data () {
    return {
      rules: {
        name: [
          {required: true, message: '请输入角色英文名称', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        name_cn: [
          {required: true, message: '请输入角色中文名称', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  computed: {
    // 获取该条编辑角色信息
    ...mapState({
      editData: state => state.role.detail
    }),
    id () {
      return this.$route.params.id
    }
  },
  mounted () {
    this.getRoleDetail()
  },
  methods: {
    // 获取角色详情
    async getRoleDetail () {
      let payload = {
        id: this.id
      }
      await this.$store.dispatch('role/roleInfo', payload)
    },
    // 后台编辑角色 使用element中的form表单
    editRole (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store.dispatch('role/editRole', this.editData).then(res => {
            notify.success(res.msg)
            this.$router.push('/role/list')
          }).catch(() => {})
        } else {
          return false
        }
      })
    },
    goBack () {
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped lang="scss">
@import "../../../assets/scss/base.scss";
.wrapper{
  .w500 {
    width: 500px;
  }
  .w100 {
    width: 100px;
  }
}
</style>